import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import http from '../../http/index'

const initialState: { value: any } = {
  value: {
    users: [],
  },
};


try {
  const list_str = localStorage.getItem("otherUser")
  if (list_str) {
    initialState.value.users = JSON.parse(list_str);
  }
} catch (error) {
  console.error('Error initializing conversation state:', error);
}

export const addUser: any = createAsyncThunk('/otherUser/add', async (id) => {
  const response = await http.get(`/findUserById?id=${id}`);
  return { user: response.data };
})



export const otherUserSlice = createSlice({
  name: "otherUser",
  initialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(addUser.fulfilled, (state, action) => {  
      const {user} = action.payload;
      const otherUserStr = localStorage.getItem("otherUser");
      const array:any[] = otherUserStr ? JSON.parse(otherUserStr) : [];
      const index = array.findIndex((item:any)=> item.userId == user.userId);
      index == -1 ? array.push(user) : array[index]= user;
      state.value = {users: array};
      localStorage.setItem("otherUser",JSON.stringify(array))
    });
  },
})

export const { } = otherUserSlice.actions;

export default otherUserSlice.reducer